﻿using Oracle.DataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WooCoo.Extension;

namespace WooCoo.Data.DataProvider
{
    public class OracleProvider : IDataProvider
    {
        private static readonly Regex ReParameterName = new Regex(@"{(?<number>\d+)}", RegexOptions.Compiled);

        public string DbParmChar
        {
            get { return ":"; }
        }

        public string FormatSql(string commonSql, int startIndex)
        {
            if (startIndex == 0)
                return ReParameterName.Replace(commonSql, ":P${number}");
            else
                return ReParameterName.Replace(commonSql, m => { return ":P" + (Convert.ToInt32(m.Value) + startIndex).ToString(); });
        }

        public System.Data.IDataParameter CreateParameter(string parameterName, object value, System.Data.ParameterDirection direction)
        {
            OracleParameter oracleParameter = new OracleParameter();
            oracleParameter.ParameterName = parameterName;
            if (direction != ParameterDirection.Output)
            {
                if (value != null)
                    oracleParameter.Value = value;
                else
                    oracleParameter.Value = DBNull.Value;
            }
            oracleParameter.Direction = direction;
            return oracleParameter;
        }

        public System.Data.IDataParameter CreateParameter(string parameterName, object value, Type type, System.Data.ParameterDirection direction, int size)
        {
            OracleParameter oracleParameter = new OracleParameter();
            oracleParameter.ParameterName = parameterName;
            if (size != -1)
            {
                oracleParameter.Size = size;
            }
            if (direction != ParameterDirection.Output)
            {
                if (value != null)
                    oracleParameter.Value = value;
                else
                    oracleParameter.Value = DBNull.Value;
            }
            if (type == typeof(Object))
            {
                oracleParameter.OracleDbType = OracleDbType.RefCursor;
            }
            else
            {
                oracleParameter.DbType = type.GetDbType();
            }
            oracleParameter.Direction = direction;
            return oracleParameter; ;
        }


        public string ResolveToSqlString(object value)
        {
            throw new NotImplementedException();
        }
    }
}
